home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / httpheaders.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  12.7 KB  |  304 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. """
  5. HTTP Header Parsing and Representation
  6.  
  7. The Headers() class wraps the HTTP Header Types, allowing easy and automated
  8. access to them. It can be instantiated with an argument of either a
  9. rfc822.Message instance, or a string containing headers to be parsed. 
  10.  
  11. Once the headers have been parsed (or an empty instance has been created), 
  12. each header can be accessed as an attribute. Dashes ('-') in the header's
  13. name should be converted to underscores ('_'), and the names are not 
  14. case-sensitive.
  15.  
  16. Depending on a particular header's type, it may be accessed as a string,
  17. integer, list or dictionary; for full details, look at the header's doc
  18. string.
  19.  
  20. The headers may be printed by calling the __repr__ method.
  21.  
  22. Finally, the putheaders() method can be used to pass the headers back
  23. to the specified httplib object, using its putheader() method.
  24.  
  25. The DemandHeaders class operates in a similar manner, except that headers are
  26. only parsed if they are modified.
  27.  
  28. Note that although the header classes attempt to format their contents
  29. correctly, they do not enforce HTTP compliance; the user should be familiar
  30. with the specification (RFC 2616).
  31. """
  32. import rfc822
  33. import sys
  34. import re
  35. from string import lower, join, split, replace
  36. from UserDict import UserDict
  37. from httpheadertypes import *
  38. __version__ = '0.61'
  39. DATA = intern('data')
  40. SEND_ENTITY = intern('send_entity')
  41. entity_headers = [
  42.     'Allow',
  43.     'Content-Encoding',
  44.     'Content-Language',
  45.     'Content-Length',
  46.     'Content-Location',
  47.     'Content-MD5',
  48.     'Content-Range',
  49.     'Content-Type',
  50.     'Expires',
  51.     'Last-Modified']
  52. linesplitter = re.compile('(?:\r\n)|\n')
  53. starting_whitespace = re.compile('^\\s')
  54.  
  55. class Headers(UserDict):
  56.     '''
  57. \tContains a dictionary of Header instances, keyed by header name
  58. \t(case-insensitive).
  59.  
  60. \tCan be instantised with a rfc822.Message object, or text of the headers,
  61. \tas the argument.
  62. \t'''
  63.     
  64.     def __init__(self, message = None):
  65.         UserDict.__init__(self)
  66.         self.send_entity = 1
  67.         if message != None:
  68.             self.parse(message)
  69.         
  70.  
  71.     
  72.     def parse(self, message):
  73.         if isinstance(message, rfc822.Message):
  74.             header_list = message.headers
  75.         else:
  76.             header_list = linesplitter.split(message)
  77.         prev_header = None
  78.         for line in header_list:
  79.             if starting_whitespace.search(line):
  80.                 value = strip(line)
  81.                 if prev_header:
  82.                     self.data[prev_header] = self.data[prev_header] + value
  83.                     continue
  84.                 else:
  85.                     self.handle_exception('parse orphan line', line)
  86.             
  87.             
  88.             try:
  89.                 (k, v) = split(line, ':', 1)
  90.                 (header_name, value) = (get_header_name(strip(k)), strip(v))
  91.                 if self.data.has_key(header_name) and isinstance(self.data[header_name], List):
  92.                     self.data[header_name] = self.data[header_name] + value
  93.                 else:
  94.                     self.data[header_name] = header_names.get(header_name, UnknownHeader)(value)
  95.                 prev_header = header_name
  96.             continue
  97.             except StandardError:
  98.                 msg = None
  99.                 self.handle_exception('parse', line)
  100.                 continue
  101.             
  102.  
  103.         
  104.  
  105.     
  106.     def __getitem__(self, key):
  107.         header_name = get_header_name(key)
  108.         if not self.data.has_key(header_name):
  109.             self.data[header_name] = header_names.get(header_name, UnknownHeader)()
  110.         
  111.         return self.data[header_name]
  112.  
  113.     
  114.     def __setitem__(self, key, item):
  115.         header_name = get_header_name(key)
  116.         self.data[header_name] = header_names.get(header_name, UnknownHeader)(item)
  117.  
  118.     
  119.     def __delitem__(self, key):
  120.         del self.data[get_header_name(key)]
  121.  
  122.     
  123.     def __getattr__(self, key):
  124.         return self[replace(key, '_', '-')]
  125.  
  126.     
  127.     def __setattr__(self, key, item):
  128.         if key in [
  129.             DATA,
  130.             SEND_ENTITY]:
  131.             self.__dict__[key] = item
  132.         else:
  133.             self[replace(key, '_', '-')] = item
  134.  
  135.     
  136.     def __delattr__(self, key):
  137.         del self[replace(key, '_', '-')]
  138.  
  139.     
  140.     def has_key(self, key):
  141.         return self.data.has_key(get_header_name(key))
  142.  
  143.     
  144.     def get(self, key, default):
  145.         return self.data.get(get_header_name(key), default)
  146.  
  147.     
  148.     def __str__(self):
  149.         return repr(self)
  150.  
  151.     
  152.     def __repr__(self):
  153.         o = []
  154.         for header, obj in self.data.items():
  155.             if not (self.send_entity) and header in entity_headers:
  156.                 continue
  157.             
  158.             
  159.             try:
  160.                 if obj._is_foldable:
  161.                     val = repr(obj)
  162.                     if val:
  163.                         o.append('%s: %s' % (header, val))
  164.                     
  165.                 else:
  166.                     for line in obj.data:
  167.                         val = repr(line)
  168.                         if not val:
  169.                             continue
  170.                         
  171.                         o.append('%s: %s' % (header, val))
  172.                 except StandardError:
  173.                     obj._is_foldable
  174.                     args = obj._is_foldable
  175.                     self.handle_exception('repr', header)
  176.                     continue
  177.                 
  178.             return join(o, '\r\n')
  179.             return None
  180.  
  181.  
  182.     
  183.     def putheaders(self, httpobj):
  184.         ''' put contained headers into httpobj using its putheader() meth. '''
  185.         for header, obj in self.data.items():
  186.             httpobj.putheader(header, repr(obj))
  187.         
  188.  
  189.     
  190.     def handle_exception(self, what, info):
  191.         '''
  192. \t\tHandles parsing and repr errors (with bad headers or values). 
  193. \t\tRaise an exception to stop processing; to continue, log the error
  194. \t\tas you wish.
  195. \t\t'''
  196.         exception = sys.exc_info()
  197.         exception[1].args = (exception[1].args, info)
  198.         raise exception[1]
  199.  
  200.  
  201.  
  202. class DemandHeaders(Headers):
  203.     """
  204. \tHeaders are only parsed on demand - more efficient if you don't access
  205. all headers, but need to output them.
  206. """
  207.     
  208.     def __init__(self, message = None):
  209.         Headers.__init__(self, message = None)
  210.         self.data = _DemandHeaderDict()
  211.         if message != None:
  212.             self.parse(message)
  213.         
  214.  
  215.     
  216.     def parse(self, message):
  217.         if isinstance(message, rfc822.Message):
  218.             header_list = message.headers
  219.         else:
  220.             header_list = linesplitter.split(message)
  221.         prev_header = None
  222.         for line in header_list:
  223.             if starting_whitespace.search(line):
  224.                 value = strip(line)
  225.                 if prev_header:
  226.                     self.data.data[prev_header].append(value)
  227.                     continue
  228.                 else:
  229.                     self.handle_exception('parse orphan line', line)
  230.             
  231.             
  232.             try:
  233.                 (k, v) = split(line, ':', 1)
  234.                 (header_name, value) = (get_header_name(strip(k)), strip(v))
  235.                 prev_header = header_name
  236.                 if self.data.data.has_key(header_name):
  237.                     self.data.data[header_name].append(value)
  238.                 else:
  239.                     self.data[header_name] = [
  240.                         value]
  241.             continue
  242.             except StandardError:
  243.                 msg = None
  244.                 self.handle_exception('parse', line)
  245.                 continue
  246.             
  247.  
  248.         
  249.  
  250.     
  251.     def __repr__(self):
  252.         o = []
  253.         for header in self.data.data.keys():
  254.             obj = self.data[header]
  255.             if not (self.send_entity) and header in entity_headers:
  256.                 continue
  257.             
  258.             if type(obj) is type([]):
  259.                 for hdr in obj:
  260.                     o.append('%s: %s' % (header, hdr))
  261.                 
  262.             
  263.             try:
  264.                 if obj._is_foldable:
  265.                     o.append('%s: %s' % (header, repr(obj)))
  266.                 else:
  267.                     for line in obj.data:
  268.                         o.append('%s: %s' % (header, repr(line)))
  269.                 except Exception:
  270.                     obj._is_foldable
  271.                     args = obj._is_foldable
  272.                     self.handle_exception('repr', header)
  273.                     continue
  274.                 
  275.             return join(o, '\r\n')
  276.             return None
  277.  
  278.  
  279.  
  280.  
  281. class _DemandHeaderDict(UserDict):
  282.     
  283.     def __getitem__(self, header_name):
  284.         hdrlist = self.data[header_name]
  285.         if type(hdrlist) is type([]):
  286.             if issubclass(header_names.get(header_name, UnknownHeader), List):
  287.                 self.data[header_name] = header_names.get(header_name, UnknownHeader)(hdrlist[0])
  288.                 for value in hdrlist[1:]:
  289.                     self.data[header_name] = self.data[header_name] + value
  290.                 
  291.             else:
  292.                 self.data[header_name] = header_names.get(header_name, UnknownHeader)(hdrlist[-1])
  293.         
  294.         return self.data[header_name]
  295.  
  296.     
  297.     def get(self, key, failobj = None):
  298.         if self.data.has_key(key):
  299.             return self[key]
  300.         else:
  301.             return failobj
  302.  
  303.  
  304.